package com.qqtech.qquan.circle.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.admin.context.AdminPage;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.exception.BizzException;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.circle.enums.CircleBaseStatusDictEnum;
import com.qqtech.qquan.circle.enums.CircleBaseTypeDictEnum;
import com.qqtech.qquan.circle.enums.CircleFuncTypeDictEnum;
import com.qqtech.qquan.circle.model.CircleBase;
import com.qqtech.qquan.circle.model.CircleBaseQuery;
import com.qqtech.qquan.circle.model.CircleBaseVo;
import com.qqtech.qquan.circle.model.CircleInfoVo;
import com.qqtech.qquan.circle.service.CircleBaseService;
import com.qqtech.qquan.circle.service.CircleInfoService;
import com.qqtech.qquan.community.model.CommunityBaseQuery;
import com.qqtech.qquan.community.model.CommunityBaseVo;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.sys.controller.BaseAdminController;
import com.qqtech.qquan.sys.model.SysAreaVo;
import com.qqtech.qquan.sys.service.SysAreaService;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.service.UserBaseService;

@Controller
@RequestMapping(value = "/circle/base")
public class CircleBaseController extends BaseAdminController {
	@Resource
	private CircleBaseService circleBaseService;
	@Resource
	private CircleInfoService circleInfoService;
	@Resource
	private UserBaseService userBaseService;
	@Resource
	private CommunityBaseService communityBaseService;
	@Resource
	private SysAreaService sysAreaService;
	
	@Override
	protected BaseService<CircleBase> getBaseService() {
		return circleBaseService;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list() {
		return "/circle/circleBase-list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(CircleBaseQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		query.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		List<Integer> includeFunctypeList = Lists.newArrayList();
		includeFunctypeList.add(CircleFuncTypeDictEnum.ALL.getCode());
		includeFunctypeList.add(CircleFuncTypeDictEnum.TOPICONLY.getCode());
		query.setIncludeFuncTypes(includeFunctypeList);//去掉群聊
		
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(), new PageOrder(Direction.DESC, "newAt"));
		Page<CircleBaseVo> page = circleBaseService.queryPageListAdmin(query, pageKit);
		UserBaseVo userBaseVo = null;
		CircleInfoVo circleInfoVo = null;
		SysAreaVo sysAreaVo = null;//地区
		for (CircleBaseVo circleVo : page) {
			userBaseVo = userBaseService.getById(circleVo.getCreatorId());//圈主
			circleInfoVo = circleInfoService.getById(circleVo.getId());//圈子
			if (null != userBaseVo) {
				circleVo.setCreatorName(userBaseVo.getNick());
			}
			if(null!= circleInfoVo){
				circleVo.setPv(circleInfoVo.getPv());
				circleVo.setMemberCount(circleInfoVo.getMemberCount());
				circleVo.setTopicCount(circleInfoVo.getTopicCount());
			}
			if(circleVo.getCityId()!=null){
				sysAreaVo = sysAreaService.getById(circleVo.getCityId());
				circleVo.setCityName(sysAreaVo ==null ? "不限": sysAreaVo.getName());//城市名称
			}
			setCommunityNames4Circle(circleVo);
		}
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	/**
	 * 附上圈子的社区名称【含扩展社区】
	 * @param circleVo
	 */
	private void setCommunityNames4Circle(CircleBaseVo circleVo){
		Integer communityId = circleVo.getCommunityId();
		if(communityId!=null){
			CommunityBaseVo community0 =communityBaseService.getById(communityId);
			if(community0!=null){
				circleVo.setCommunityName(community0.getName());//创始社区
			}
		}
		
		String extComStr = circleVo.getExtCommunityIds();
		List<Integer> extComIdList = Lists.newArrayList();		
		if(StringUtil.isNotBlank(extComStr)){
			String[] strExtComIdList = extComStr.split(";");
			extComIdList = getIntegerCommunityIds(strExtComIdList);
		}
		if(!extComIdList.isEmpty()){
			CommunityBaseQuery communityQ = new CommunityBaseQuery();
			communityQ.setIncludeIds(extComIdList);
			List<CommunityBaseVo> communityList = communityBaseService.queryList(communityQ);
			circleVo.setExtCommunityNames(getCommunityNames(communityList));
		}
	}
	
	@RequestMapping(value = "/detail")
	public String detail(Integer id, Model model) {
		CircleBaseVo circleVo = circleBaseService.getById(id);
		UserBaseVo userBaseVo = userBaseService.getById(circleVo.getCreatorId());
		if(userBaseVo!=null){
			circleVo.setCreatorName(userBaseVo.getNick());
		}
		setCommunityNames4Circle(circleVo);
		CircleInfoVo circleInfoVo = circleInfoService.getById(id);
		if(circleInfoVo!=null){
			circleVo.setPv(circleInfoVo.getPv());
			circleVo.setMemberCount(circleInfoVo.getMemberCount());
			circleVo.setTopicCount(circleInfoVo.getTopicCount());
			if(circleVo.getCityId()!=null){
				SysAreaVo sysAreaVo = sysAreaService.getById(circleVo.getCityId());//地区
				circleVo.setCityName(sysAreaVo ==null ? "不限": sysAreaVo.getName());//城市名称
			}
		}
		model.addAttribute("circleVo", circleVo);
		return "/circle/circleBase-detail";
	}
	
	
	@RequestMapping(value = "/toUpdate/{circleId}", method = RequestMethod.GET)
	public String toUpdate(@PathVariable Integer circleId, HttpServletRequest request, HttpServletResponse response) {
		CircleBase circle = circleBaseService.getById(circleId);
		request.setAttribute("circle", circle);
		return "/circle/circleBase-update";
	}
	
	@RequestMapping(value = "/doUpdate/{circleId}", method = RequestMethod.POST)
	@ResponseBody
	public Result doUpdate(@PathVariable Integer circleId, CircleBase circle) {
		CircleBase circleDb = circleBaseService.getById(circleId);
		Result ret = new Result();
		if (circleDb == null) {
			ret.addErr("圈子不存在");
		} else {
			if (StringUtil.isBlank(circle.getName())) {
				ret.addErr("请输入圈子名称");
			}
		}
		if (ret.checkForm()) {
			CircleBase circle4update = new CircleBase();
			circle4update.setId(circleId);
			circle4update.setName(circle.getName());
			circle4update.setRemark(circle.getRemark());
			circleBaseService.updateById(circle4update);
		}
		return ret;
	}
	
	@RequestMapping(value = "/toAdd", method = RequestMethod.GET)
	public String toUpdate() {
		return "/circle/circleBase-add";
	}
	
	/**
	 * 后台添加官方圈子
	 * @param circle
	 * @return
	 * @throws BizzException 
	 */
	@RequestMapping(value = "/doAdd", method = RequestMethod.POST)
	@ResponseBody
	public Result doAdd(CircleBase circle) throws BizzException {
		Result ret = new Result();
		if (StringUtil.isBlank(circle.getName())) {
			ret.addErr("请输入圈子名称");
		}
		if (StringUtil.isBlank(circle.getRemark())) {
			ret.addErr("请输入圈子描述");
		}
		if (StringUtil.isBlank(circle.getLogo())) {
			ret.addErr("请上传圈子图片");
		}
		if (ret.checkForm()) {
			CircleBase circle4offical = new CircleBase();
			circle4offical.setType(CircleBaseTypeDictEnum.OFFICIAL.getCode());
			circle4offical.setName(circle.getName());
			circle4offical.setRemark(circle.getRemark());
			circle4offical.setLogo(circle.getLogo());
			circle4offical.setCreatorId(0);//这个用户不存在
			circleBaseService.addCircle(circle4offical);//添加官方圈子
		}
		return ret;
	}
	
	/**
	 * 推荐圈子
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/recommend")
	@ResponseBody
	public Result recommend(Integer id, Integer recommendOidx) {
		Result ret = new Result();
		int updateCount = circleBaseService.setRecommend(id, recommendOidx);
		if(updateCount!=1){
			ret.addErr("推荐圈子失败");
		}
		return ret;
	}
	/**
	 * 抽奖上架
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/upLottery")
	@ResponseBody
	public Result upLottery(Integer id) {
		Result ret = new Result();
		CircleBase circleBase=new CircleBase();
		circleBase.setIsLottery(YesNoEnum.YES.getCode());
		circleBase.setId(id);
		circleBaseService.updateById(circleBase);
		return ret;
	}
	/**
	 * 抽奖下架
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downLottery")
	@ResponseBody
	public Result downLottery(Integer id) {
		Result ret = new Result();
		CircleBase circleBase=new CircleBase();
		circleBase.setIsLottery(YesNoEnum.NO.getCode());
		circleBase.setId(id);
		circleBaseService.updateById(circleBase);
		return ret;
	}
	/**
	 * 取消推荐圈子
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/unRecommend")
	@ResponseBody
	public Result unRecommend(Integer id) {
		Result ret = new Result();
		int updateCount = circleBaseService.setUnRecommend(id);
		if(updateCount!=1){
			ret.addErr("取消推荐圈子失败");
		}
		return ret;
	}
	
	/**
	 * 审核通过
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/auditPass")
	@ResponseBody
	public Result auditPass(Integer id) {
		Result ret = new Result();
		int updateCount = circleBaseService.auditPass(id);
		if(updateCount!=1){
			ret.addErr("审核通过-失败");
		}
		return ret;
	}
	
	/**
	 * 取消审核通过
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/undoAudit")
	@ResponseBody
	public Result undoAudit(Integer id) {
		Result ret = new Result();
		int updateCount = circleBaseService.undoAudit(id);
		if(updateCount!=1){
			ret.addErr("审核通过-失败");
		}
		return ret;
	}
	/**
	 * 审核不通过
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/auditNotPass")
	@ResponseBody
	public Result auditNotPass(Integer id) {
		Result ret = new Result();
		int updateCount = circleBaseService.auditNotPass(id);
		if(updateCount!=1){
			ret.addErr("审核不通过-失败");
		}
		return ret;
	}
	
	/**
	 * 返回社区字符串【以、号隔开】
	 * @param communityList
	 * @return
	 */
	private String getCommunityNames(List<CommunityBaseVo> communityList){
		String names = "";
		if(communityList!=null && communityList.size() >0){
			for(CommunityBaseVo community : communityList){
				names += community.getName() +"、";
			}
		}
		if(StringUtil.isNotBlank(names)){
			names = names.substring(0, names.length()-1);
		}
		return names;
	}

	/**
	 * List<String>转换为List<Integer>
	 * @param strCommunityIds
	 * @return
	 */
	private List<Integer> getIntegerCommunityIds(String[] strCommunityIds){
		List<Integer> communityIds = Lists.newArrayList();
		if(strCommunityIds!=null && strCommunityIds.length >0){
			for(String strCommunityId : strCommunityIds){
				communityIds.add(Integer.parseInt(strCommunityId));
			}
		}
		
		return communityIds;
	}
}
